package com.liuwei.protocol;

import com.liuwei.common.Invocation;
import com.liuwei.register.LocalRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.Provider;
import java.util.Properties;

// 实际请求中心
public class HttpServerHandler {
    public void handler(HttpServletRequest req, HttpServletResponse resp){
      try {
          // 反序列化，拿到接口名字
          Invocation invocation =(Invocation) new ObjectInputStream(req.getInputStream()).readObject();
          String interfaceName = invocation.getInterfaceName();
          // 获取"C:\\Users\\dell\\IdeaProjects\\LiuWeiRPC\\RPC\\src\\main\\resources\\version.txt"文件下的默认版本号
          Properties properties = new Properties();
          FileReader fr = null;
          try {
              fr = new FileReader("C:\\Users\\dell\\IdeaProjects\\LiuWeiRPC\\RPC\\src\\main\\resources\\version.txt");
              //从.txt文件中获取键值对的properties对象
              properties.load(fr);
              fr.close();
          } catch (FileNotFoundException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
          // 打印默认版本号
          String version = properties.getProperty("version");
          if(version == null){
              version = "1.0";
          }
          System.out.println(version);
          Class classImpl = LocalRegister.get(interfaceName,version);
          // 获取远端调用的方法
          Method method = classImpl.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
          // 反射执行
          String result = (String)method.invoke(classImpl.newInstance(), invocation.getParameters());
          // 将反射执行的结果放在IOUtils中阻塞存储一下，以备使用
          IOUtils.write(result,resp.getOutputStream());
      }catch (IOException e){
          e.printStackTrace();
      }catch (ClassNotFoundException e){
          e.printStackTrace();
      } catch (NoSuchMethodException e) {
          throw new RuntimeException(e);
      } catch (InvocationTargetException e) {
          throw new RuntimeException(e);
      } catch (IllegalAccessException e) {
          throw new RuntimeException(e);
      } catch (InstantiationException e) {
          throw new RuntimeException(e);
      }
    }
}
